package cn.growthgate.fgo.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import cn.growthgate.fgo.common.base.BaseServiceImpl;
import cn.growthgate.fgo.core.shiro.SimpleUser;
import cn.growthgate.fgo.entity.User;
import cn.growthgate.fgo.entity.UserRole;
import cn.growthgate.fgo.entity.vo.UserVo;
import cn.growthgate.fgo.mapper.UserMapper;
import cn.growthgate.fgo.service.IUserService;
import cn.growthgate.fgo.util.ImageUtils;
import cn.growthgate.fgo.util.SecretUtils;
import cn.growthgate.fgo.util.StringUtils;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author GrowthGate
 * @since 2019-01-20
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements IUserService {

	@Override
	public User getByUsername(String username) {
		User user = new User();
		user.setUsername(username);
		return baseMapper.selectOne(user);
	}

	@Override
	public User getByUsernameAndPassword(String username, String password) {
		User user = getByUsername(username);
		if (user == null) {
			return null;
		}
		password = SecretUtils.pbkdf2WithHmacSHA512(password, user.getSalt());
		boolean isPass = StringUtils.equals(password, user.getPassword());
		return isPass ? user : null;
	}

	@Override
	public User getByName(String name) {
		User user = new User();
		user.setName(name);
		return baseMapper.selectOne(user);
	}

	@Override
	public SimpleUser transformSimpleUser(User user) {
		SimpleUser simpleUser = new SimpleUser();
		simpleUser.setId(user.getId());
		simpleUser.setUsername(user.getUsername());
		simpleUser.setName(user.getName());
		simpleUser.setAvatarUrl(ImageUtils.getImageUrl(user.getAvatar()));
		return simpleUser;
	}

	@Override
	public boolean create(User user) {
		String password = user.getPassword();
		setPassword(user, password);
		return insert(user);
	}

	@Override
	public void setPassword(User user, String password) {
		String salt = StringUtils.getRandomUUID();
		password = SecretUtils.pbkdf2WithHmacSHA512(password, salt);

		user.setPassword(password);
		user.setSalt(salt);
	}

	@Override
	public UserVo transformVo(User user) {
		UserVo vo = new UserVo();
		vo.setId(user.getId());
		vo.setAvatar(user.getAvatar());
		vo.setUsername(user.getUsername());
		vo.setName(user.getName());
		vo.setSex(user.getSex());
		vo.setClient(user.getClient());
		vo.setPyCode(user.getPyCode());
		vo.setStatus(user.getStatus());
		vo.setAddtime(user.getAddtime());
		vo.setLastLoginTime(user.getLastLoginTime());
		List<UserRole> userRoles = baseMapper.getRoles(user);
		vo.setRoles(userRoles.stream().map(userRole -> userRole.getRole()).collect(Collectors.toList()));
		return vo;
	}

}
